package org.jeecg.modules.mp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sf.json.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.mp.entity.JwWebJwid;
import org.jeecg.modules.mp.mapper.JwWebJwidMapper;
import org.jeecg.modules.mp.service.IJwWebJwidService;
import org.jeewx.api.core.common.AccessToken;
import org.jeewx.api.core.common.WxstoreUtils;
import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.core.util.WeiXinConstant;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description: 公众号
 * @Author: jeecg-boot
 * @Date:   2022-04-12
 * @Version: V1.0
 */
@Service
public class JwWebJwidServiceImpl extends ServiceImpl<JwWebJwidMapper, JwWebJwid> implements IJwWebJwidService {

    private static String get_tamplate_list = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=ACCESS_TOKEN";


    public String getTemplateList(String accessToken) throws WexinReqException {
        String msg = "";
        if (accessToken != null) {
            String requestUrl = get_tamplate_list.replace("ACCESS_TOKEN", accessToken);
            JSONObject result = WxstoreUtils.httpRequest(requestUrl, "GET", (String)null);
            Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE);
            if (error != null) {
                msg = result.getString(WeiXinConstant.RETURN_ERROR_INFO_MSG);
            } else {
                msg = result.toString();
            }
        }

        return msg;
    }

    @Override
    public Result<?> authToken(JwWebJwid jwWebJwid) {
        JwWebJwid webJwid = baseMapper.selectById(jwWebJwid.getId());
        AccessToken at=new AccessToken(webJwid.getWeixinAppid(),webJwid.getWeixinAppsecret());
        //获取AccessToken
        String newAccessToken = at.getNewAccessToken();
        if(null != newAccessToken){
            webJwid.setAccessToken(newAccessToken);
            webJwid.setTokenGettime(new Date());
            baseMapper.updateById(webJwid);
            return Result.OK("授权成功");
        }else{
            return Result.error("授权异常");
        }
    }
}
